'use client';

import {
  type ChangeEvent,
  type FormEvent,
  useContext,
  useEffect,
  useState,
} from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import diff from 'microdiff';
import type {
  IConfigEmail,
  IConfigEmailItem,
  IDifference,
  IUpdateEmailConfigBody,
} from '@/interfaces';
import type { IConfigEmailContentType, TBody } from '@/types';
import { updateEmailConfig } from '@/services/api';
import classNames from 'classnames';
import useToast from '@/hooks/useToast';
import { ConfigAdminContext } from '@/contexts/admin/config';
import { getDiffData, getFilterData, isEmpty } from '@/lib/tool';

export default function UpdateConfigEmail(
  this: any,
  {
    details,
  }: {
    details: IConfigEmail;
  },
) {
  const [tabIndex, setTabIndex] = useState(1);

  function onClickTab(index: number) {
    setTabIndex(index);
  }

  return (
    <div className="row">
      <div className="col">
        <div className="vstack gap-4">
          <div>
            <p>温馨提示：</p>
            <ol className="text-muted">
              <li>
                邮箱开通：
                <a
                  target="_blank"
                  href="https://console.cloud.tencent.com/ses"
                  rel="noreferrer"
                >
                  腾讯云
                </a>
                &nbsp;/&nbsp;
                <a
                  target="_blank"
                  href="https://dm.console.aliyun.com/#/directmail/Home/cn-hangzhou"
                  rel="noreferrer"
                >
                  阿里云
                </a>
              </li>
              <li>
                验证码类型/长度：请注意查看相应服务商要求，例如有的供应商验证码只能是纯数字，长度
                4 位
              </li>
              <li>
                请替换表单内容为正确内容，如果已经替换请忽略，填写可以结合参考相应服务商文档中的描述或示例
              </li>
            </ol>
          </div>

          <nav className="nav nav-pills flex-column flex-sm-row">
            <a
              onClick={onClickTab.bind(this, 1)}
              className={classNames(
                'flex-sm-fill text-sm-center nav-link cursor-pointer',
                {
                  'bg-light': tabIndex === 1,
                },
              )}
            >
              登录
            </a>
            <a
              onClick={onClickTab.bind(this, 2)}
              className={classNames(
                'flex-sm-fill text-sm-center nav-link cursor-pointer',
                {
                  'bg-light': tabIndex === 2,
                },
              )}
            >
              注册
            </a>
            <a
              onClick={onClickTab.bind(this, 3)}
              className={classNames(
                'flex-sm-fill text-sm-center nav-link cursor-pointer',
                {
                  'bg-light': tabIndex === 3,
                },
              )}
            >
              验证
            </a>
          </nav>

          {tabIndex === 1 && <FormItem type="LOGIN" details={details} />}

          {tabIndex === 2 && <FormItem type="REGISTER" details={details} />}

          {tabIndex === 3 && <FormItem type="VERIFY" details={details} />}
        </div>
      </div>
    </div>
  );
}

const FormItem = ({
  type,
  details,
}: {
  type: IConfigEmailContentType;
  details: IConfigEmail;
}) => {
  const { show } = useToast();
  const [form, setForm] = useState<IConfigEmailItem>({
    service: 'TENCENT',
    aliyun: {
      enable: false,
      expire: 'PT5M',
      total: 5,
      interval: 'PT1M',
      recoveryTime: 'PT24H',
      length: 4,
      alphanumeric: false,
      alphabetic: false,
      ascii: false,
      numeric: true,
      accessKeyId: '',
      accessKeySecret: '*********',
      endpoint: '',
      accountName: '',
      addressType: 0,
      replyToAddress: false,
      subject: '',
      toAddress: '',
      action: '',
      clickTrace: '',
      fromAlias: '',
      htmlBody: '',
      tagName: '',
      textBody: '',
      replyAddress: '',
      replyAddressAlias: '',
    },
    tencent: {
      enable: false,
      expire: 'PT5M',
      total: 5,
      interval: 'PT1M',
      recoveryTime: 'PT24H',
      length: 4,
      alphanumeric: false,
      alphabetic: false,
      ascii: false,
      numeric: true,
      secretId: '',
      secretKey: '*********',
      action: '',
      version: '',
      endpoint: '',
      region: '',
      fromEmailAddress: '',
      destination: [],
      subject: '',
      replyToAddresses: '',
      template: {
        templateId: 1,
        templateData: '',
      },
      simple: '',
      attachments: '',
      unsubscribe: '',
      triggerType: 0,
    },
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const [tabIndex, setTabIndex] = useState(1);
  const [subTabIndex, setSubTabIndex] = useState(1);
  const queryClient = useQueryClient();
  const context = useContext(ConfigAdminContext);

  const updateEmailConfigMutation = useMutation(
    async (variables: TBody<IUpdateEmailConfigBody>) => {
      await updateEmailConfig(variables);
      await queryClient.invalidateQueries([
        '/configs',
        `/${context.updateItem?.id}`,
      ]);
    },
  );

  useEffect(() => {
    if (details) {
      const data = details.list[type];
      if (data) {
        setForm({
          service: data.service,
          tencent: { ...form.tencent, ...data.tencent },
          aliyun: { ...form.aliyun, ...data.aliyun },
        });
      }
    }
  }, [details]);
  useEffect(() => {
    if (details) {
      const data = details.list[type] || {};
      const differences = diff(data, form);
      setDifferenceData(differences);
    }
  }, [form, details]);

  function onChangeForm(
    e: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>,
  ) {
    const name = e.target.name;
    const value = e.target.value;
    const itemName = subTabIndex === 1 ? 'tencent' : 'aliyun';

    if (name === 'service') {
      setForm({
        ...form,
        service: value as any,
      });
    } else if (
      name === 'enable' ||
      name === 'alphanumeric' ||
      name === 'alphabetic' ||
      name === 'ascii' ||
      name === 'numeric'
    ) {
      setForm({
        ...form,
        [itemName]: {
          ...form[itemName],
          [name]: value === 'true',
        },
      });
    } else if (name === 'total' || name === 'length') {
      setForm({
        ...form,
        [itemName]: {
          ...form[itemName],
          [name]: parseInt(value),
        },
      });
    } else if (name === 'templateId') {
      setForm({
        ...form,
        tencent: {
          ...form.tencent,
          template: {
            ...form.tencent.template,
            templateId: parseInt(value),
          },
        },
      });
    } else {
      setForm({
        ...form,
        [itemName]: {
          ...form[itemName],
          [name]: value,
        },
      });
    }
  }

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const body = getFilterData(
        getDiffData(differenceData),
        ['secretKey', 'accessKeySecret'],
        (key, value) => {
          return !(
            (key === 'secretKey' || key === 'accessKeySecret') &&
            typeof value === 'string' &&
            value.includes('*********')
          );
        },
      );
      if (isEmpty(body)) {
        show({
          type: 'SUCCESS',
          message: '保存完成',
        });
        return;
      }

      await updateEmailConfigMutation.mutateAsync({
        data: {
          list: {
            [type]: body,
          },
        },
      });

      clearData();
      show({
        type: 'SUCCESS',
        message: '保存完成',
      });
    } catch (e) {
      updateEmailConfigMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function clearData() {
    setDifferenceData([]);
  }

  function onClickSubTab(index: number) {
    setSubTabIndex(index);
  }

  return (
    <div className="vstack gap-4">
      <nav className="nav nav-pills flex-column flex-sm-row">
        <a
          onClick={onClickSubTab.bind(this, 1)}
          className={classNames(
            'flex-sm-fill text-sm-center nav-link cursor-pointer',
            {
              'bg-light': subTabIndex === 1,
            },
          )}
        >
          腾讯云
        </a>
        <a
          onClick={onClickSubTab.bind(this, 2)}
          className={classNames(
            'flex-sm-fill text-sm-center nav-link cursor-pointer',
            {
              'bg-light': subTabIndex === 2,
            },
          )}
        >
          阿里云
        </a>
      </nav>

      {subTabIndex === 1 && (
        <form onSubmit={onClickSave} className="vstack gap-4">
          <div className="row">
            <div className="col">
              <div className="vstack gap-4">
                <div>
                  <label className="form-label">选择服务商</label>
                  <select
                    name="service"
                    value={form.service}
                    onChange={onChangeForm}
                    className="form-select"
                    aria-label="service"
                    placeholder="请选择邮箱登录使用的服务商"
                  >
                    <option value="TENCENT">腾讯云</option>
                    <option value="ALIYUN">阿里云</option>
                  </select>
                </div>

                <div>
                  <label className="form-label">是否启用</label>
                  <select
                    name="enable"
                    value={form.tencent.enable ? 'true' : 'false'}
                    onChange={onChangeForm}
                    className="form-select"
                    aria-label="enable"
                    placeholder="请选择验证码是否启用"
                  >
                    <option value="true">true</option>
                    <option value="false">false</option>
                  </select>
                </div>

                <div>
                  <label className="form-label">
                    有效期
                    <span className="text-muted">（H 小时，M 分钟，S 秒）</span>
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="expire"
                    value={form.tencent.expire}
                    onChange={onChangeForm}
                    aria-describedby="expire"
                    placeholder="请输入验证码有效期"
                  />
                </div>

                <div>
                  <label className="form-label">有效次数</label>
                  <input
                    min={1}
                    type="number"
                    className="form-control"
                    name="total"
                    value={form.tencent.total}
                    onChange={onChangeForm}
                    aria-describedby="total"
                    placeholder="请输入验证码有效次数"
                  />
                </div>

                <div>
                  <label className="form-label">
                    间隔时间
                    <span className="text-muted">（H 小时，M 分钟，S 秒）</span>
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="interval"
                    value={form.tencent.interval}
                    onChange={onChangeForm}
                    aria-describedby="interval"
                    placeholder="请输入验证码间隔时间"
                  />
                </div>

                <div>
                  <label className="form-label">
                    次数恢复时间
                    <span className="text-muted">（H 小时，M 分钟，S 秒）</span>
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="recoveryTime"
                    value={form.tencent.recoveryTime}
                    onChange={onChangeForm}
                    aria-describedby="recoveryTime"
                    placeholder="请输入验证码次数恢复时间"
                  />
                </div>

                <div>
                  <label className="form-label">长度</label>
                  <input
                    min={1}
                    type="number"
                    className="form-control"
                    name="length"
                    value={form.tencent.length}
                    onChange={onChangeForm}
                    aria-describedby="length"
                    placeholder="请输入验证码长度"
                  />
                </div>

                <div>
                  <label className="form-label">字母数字</label>
                  <select
                    name="alphanumeric"
                    value={form.tencent.alphanumeric ? 'true' : 'false'}
                    onChange={onChangeForm}
                    className="form-select"
                    aria-label="alphanumeric"
                    placeholder="请选择验证码是否为字母数字"
                  >
                    <option value="true">true</option>
                    <option value="false">false</option>
                  </select>
                </div>

                <div>
                  <label className="form-label">字母</label>
                  <select
                    name="alphabetic"
                    value={form.tencent.alphabetic ? 'true' : 'false'}
                    onChange={onChangeForm}
                    className="form-select"
                    aria-label="alphabetic"
                    placeholder="请选择验证码是否为字母"
                  >
                    <option value="true">true</option>
                    <option value="false">false</option>
                  </select>
                </div>

                <div>
                  <label className="form-label">ascii</label>
                  <select
                    name="ascii"
                    value={form.tencent.ascii ? 'true' : 'false'}
                    onChange={onChangeForm}
                    className="form-select"
                    aria-label="ascii"
                    placeholder="请选择验证码是否为 ascii"
                  >
                    <option value="true">true</option>
                    <option value="false">false</option>
                  </select>
                </div>

                <div>
                  <label className="form-label">数字</label>
                  <select
                    name="numeric"
                    value={form.tencent.numeric ? 'true' : 'false'}
                    onChange={onChangeForm}
                    className="form-select"
                    aria-label="numeric"
                    placeholder="请选择验证码是否为数字"
                  >
                    <option value="true">true</option>
                    <option value="false">false</option>
                  </select>
                </div>
              </div>
            </div>
            <div className="col">
              <div className="vstack gap-4">
                <div>
                  <label className="form-label">secretId</label>
                  <input
                    type="text"
                    className="form-control"
                    name="secretId"
                    value={form.tencent.secretId}
                    onChange={onChangeForm}
                    aria-describedby="secretId"
                    placeholder="请输入 secretId"
                  />
                </div>

                <div>
                  <label className="form-label">secretKey</label>
                  <input
                    type="password"
                    autoComplete="password"
                    className="form-control"
                    name="secretKey"
                    value={form.tencent.secretKey}
                    onChange={onChangeForm}
                    aria-describedby="secretKey"
                    placeholder="请输入 secretKey"
                  />
                </div>

                <div>
                  <label className="form-label">服务地域</label>
                  <input
                    type="text"
                    className="form-control"
                    name="region"
                    value={form.tencent.region}
                    onChange={onChangeForm}
                    aria-describedby="region"
                    placeholder="请输入服务地域"
                  />
                </div>

                <div>
                  <label className="form-label">发信邮件地址</label>
                  <input
                    type="text"
                    className="form-control"
                    name="fromEmailAddress"
                    value={form.tencent.fromEmailAddress}
                    onChange={onChangeForm}
                    aria-describedby="fromEmailAddress"
                    placeholder="请输入发信邮件地址"
                  />
                </div>

                <div>
                  <label className="form-label">邮件主题</label>
                  <input
                    type="text"
                    className="form-control"
                    name="subject"
                    value={form.tencent.subject}
                    onChange={onChangeForm}
                    aria-describedby="subject"
                    placeholder="请输入邮件主题"
                  />
                </div>

                <div>
                  <label className="form-label">邮件的回复邮件地址</label>
                  <input
                    type="text"
                    className="form-control"
                    name="replyToAddresses"
                    value={form.tencent.replyToAddresses}
                    onChange={onChangeForm}
                    aria-describedby="replyToAddresses"
                    placeholder="请输入邮件的回复邮件地址"
                  />
                </div>

                <div>
                  <label className="form-label">
                    模板 Id
                    <span className="text-muted">
                      （模板变量参数：验证码 code 和有效期 time）
                    </span>
                  </label>
                  <input
                    min={1}
                    type="number"
                    className="form-control"
                    name="templateId"
                    value={form.tencent.template.templateId}
                    onChange={onChangeForm}
                    aria-describedby="templateId"
                    placeholder="请输入模板 Id"
                  />
                </div>
              </div>
            </div>
          </div>

          <button
            type="submit"
            disabled={updateEmailConfigMutation.isLoading}
            className="btn btn-success w-25 my-4"
          >
            {updateEmailConfigMutation.isLoading && (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            )}
            更新
          </button>
        </form>
      )}

      {subTabIndex === 2 && (
        <form onSubmit={onClickSave} className="vstack gap-4">
          <div className="row">
            <div className="col">
              <div className="vstack gap-4">
                <div>
                  <label className="form-label">选择服务商</label>
                  <select
                    name="service"
                    value={form.service}
                    onChange={onChangeForm}
                    className="form-select"
                    aria-label="service"
                    placeholder="请选择邮箱登录使用的服务商"
                  >
                    <option value="TENCENT">腾讯云</option>
                    <option value="ALIYUN">阿里云</option>
                  </select>
                </div>

                <div>
                  <label className="form-label">是否启用</label>
                  <select
                    name="enable"
                    value={form.aliyun.enable ? 'true' : 'false'}
                    onChange={onChangeForm}
                    className="form-select"
                    aria-label="enable"
                    placeholder="请选择验证码是否启用"
                  >
                    <option value="true">true</option>
                    <option value="false">false</option>
                  </select>
                </div>

                <div>
                  <label className="form-label">
                    有效期
                    <span className="text-muted">（H 小时，M 分钟，S 秒）</span>
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="expire"
                    value={form.aliyun.expire}
                    onChange={onChangeForm}
                    aria-describedby="expire"
                    placeholder="请输入验证码有效期"
                  />
                </div>

                <div>
                  <label className="form-label">有效次数</label>
                  <input
                    min={1}
                    type="number"
                    className="form-control"
                    name="total"
                    value={form.aliyun.total}
                    onChange={onChangeForm}
                    aria-describedby="total"
                    placeholder="请输入验证码有效次数"
                  />
                </div>

                <div>
                  <label className="form-label">
                    间隔时间
                    <span className="text-muted">（H 小时，M 分钟，S 秒）</span>
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="interval"
                    value={form.aliyun.interval}
                    onChange={onChangeForm}
                    aria-describedby="interval"
                    placeholder="请输入验证码间隔时间"
                  />
                </div>

                <div>
                  <label className="form-label">
                    次数恢复时间
                    <span className="text-muted">（H 小时，M 分钟，S 秒）</span>
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    name="recoveryTime"
                    value={form.aliyun.recoveryTime}
                    onChange={onChangeForm}
                    aria-describedby="recoveryTime"
                    placeholder="请输入验证码次数恢复时间"
                  />
                </div>

                <div>
                  <label className="form-label">长度</label>
                  <input
                    min={1}
                    type="number"
                    className="form-control"
                    name="length"
                    value={form.aliyun.length}
                    onChange={onChangeForm}
                    aria-describedby="length"
                    placeholder="请输入验证码长度"
                  />
                </div>

                <div>
                  <label className="form-label">字母数字</label>
                  <select
                    name="alphanumeric"
                    value={form.aliyun.alphanumeric ? 'true' : 'false'}
                    onChange={onChangeForm}
                    className="form-select"
                    aria-label="alphanumeric"
                    placeholder="请选择验证码是否为字母数字"
                  >
                    <option value="true">true</option>
                    <option value="false">false</option>
                  </select>
                </div>

                <div>
                  <label className="form-label">字母</label>
                  <select
                    name="alphabetic"
                    value={form.aliyun.alphabetic ? 'true' : 'false'}
                    onChange={onChangeForm}
                    className="form-select"
                    aria-label="alphabetic"
                    placeholder="请选择验证码是否为字母"
                  >
                    <option value="true">true</option>
                    <option value="false">false</option>
                  </select>
                </div>

                <div>
                  <label className="form-label">ascii</label>
                  <select
                    name="ascii"
                    value={form.aliyun.ascii ? 'true' : 'false'}
                    onChange={onChangeForm}
                    className="form-select"
                    aria-label="ascii"
                    placeholder="请选择验证码是否为 ascii"
                  >
                    <option value="true">true</option>
                    <option value="false">false</option>
                  </select>
                </div>

                <div>
                  <label className="form-label">数字</label>
                  <select
                    name="numeric"
                    value={form.aliyun.numeric ? 'true' : 'false'}
                    onChange={onChangeForm}
                    className="form-select"
                    aria-label="numeric"
                    placeholder="请选择验证码是否为数字"
                  >
                    <option value="true">true</option>
                    <option value="false">false</option>
                  </select>
                </div>
              </div>
            </div>
            <div className="col">
              <div className="vstack gap-4">
                <div>
                  <label className="form-label">accessKeyId</label>
                  <input
                    type="text"
                    className="form-control"
                    name="accessKeyId"
                    value={form.aliyun.accessKeyId}
                    onChange={onChangeForm}
                    aria-describedby="accessKeyId"
                    placeholder="请输入 accessKeyId"
                  />
                </div>

                <div>
                  <label className="form-label">accessKeySecret</label>
                  <input
                    type="password"
                    autoComplete="password"
                    className="form-control"
                    name="accessKeySecret"
                    value={form.aliyun.accessKeySecret}
                    onChange={onChangeForm}
                    aria-describedby="accessKeySecret"
                    placeholder="请输入 accessKeySecret"
                  />
                </div>

                <div>
                  <label className="form-label">发信地址</label>
                  <input
                    type="text"
                    className="form-control"
                    name="accountName"
                    value={form.aliyun.accountName}
                    onChange={onChangeForm}
                    aria-describedby="accountName"
                    placeholder="请输入发信地址"
                  />
                </div>

                <div>
                  <label className="form-label">邮件主题</label>
                  <input
                    type="text"
                    className="form-control"
                    name="subject"
                    value={form.aliyun.subject}
                    onChange={onChangeForm}
                    aria-describedby="subject"
                    placeholder="请输入邮件主题"
                  />
                </div>

                <div>
                  <label className="form-label">发信人昵称</label>
                  <input
                    type="text"
                    className="form-control"
                    name="fromAlias"
                    value={form.aliyun.fromAlias}
                    onChange={onChangeForm}
                    aria-describedby="fromAlias"
                    placeholder="请输入发信人昵称"
                  />
                </div>

                <div>
                  <label className="form-label">
                    邮件 html 正文
                    <span className="text-muted">
                      （模板变量参数：验证码 code 和有效期 time）
                    </span>
                  </label>
                  <textarea
                    rows={6}
                    className="form-control"
                    name="htmlBody"
                    value={form.aliyun.htmlBody}
                    onChange={onChangeForm}
                    aria-describedby="htmlBody"
                    placeholder="请输入邮件 html 正文"
                  />
                </div>

                <div>
                  <label className="form-label">标签</label>
                  <input
                    type="text"
                    className="form-control"
                    name="tagName"
                    value={form.aliyun.tagName}
                    onChange={onChangeForm}
                    aria-describedby="tagName"
                    placeholder="请输入标签"
                  />
                </div>

                <div>
                  <label className="form-label">回信地址</label>
                  <input
                    type="text"
                    className="form-control"
                    name="replyAddress"
                    value={form.aliyun.replyAddress}
                    onChange={onChangeForm}
                    aria-describedby="replyAddress"
                    placeholder="请输入回信地址"
                  />
                </div>

                <div>
                  <label className="form-label">回信地址别称</label>
                  <input
                    type="text"
                    className="form-control"
                    name="replyAddressAlias"
                    value={form.aliyun.replyAddressAlias}
                    onChange={onChangeForm}
                    aria-describedby="replyAddressAlias"
                    placeholder="请输入回信地址别称"
                  />
                </div>
              </div>
            </div>
          </div>

          <button
            type="submit"
            disabled={updateEmailConfigMutation.isLoading}
            className="btn btn-success w-25 my-4"
          >
            {updateEmailConfigMutation.isLoading && (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            )}
            更新
          </button>
        </form>
      )}
    </div>
  );
};
